import math
from typing import List

import db as crud
from flask_main import group_items_by_oid, get_batch_num, search_batches_GP, pack
from load_files import load_pieces_from_flask
from order import Order
from params import Piece, BoardCategory


def calc_opt_ratio(searchlists: List[Piece]):
    config = crud.get_config()
    cut_rim = config.cut_rim
    batch_size1 = config.batch_size
    items1, all_mat_names, dic, depart_num, optimization_type, datatime = load_pieces_from_flask(searchlists)
    # print(dic)
    for mat_names in all_mat_names:
        print('----------------------------{0}开始优化---------------------------'.format(mat_names))
        items = dic[mat_names]
        orders = []
        oids_names = sorted(list(set([item.oid for item in items])))
        # 找出所有的item的订单号，订单号不重复
        # sorted() 函数对所有可迭代的对象进行排序操作
        # set() 函数创建一个无序不重复元素集
        # oids_names订单名字组成的list
        grps = group_items_by_oid(items)
        # 订单名字（里面包含每一个该订单的所有ITem详情）
        real_items = []
        for name in oids_names:
            order_items = grps[name]
            orders.append(Order(oids=name, num=len(order_items), items=order_items))
            real_items.extend(order_items)
        items = real_items
        print('{0}   一共有{1}个order,一共包含{2}个piece'.format(mat_names, len(orders), len(items)))
        now_M, now_ratio, square_workpieces, total_square = pack(items, name='所有订单一个批次的利用率优化', cut_rim=cut_rim,
                                                                 print_info=True)
        best_cnt_boards = len(now_M.bins)
        print('{0}   所有的做成一个批次消耗的板材数为{1}利用率为{2}'.format(mat_names, len(now_M.bins), now_ratio))

        batch_num = get_batch_num(len(items), batch_size1)

        batch_size = math.floor(len(items) / batch_num)
        print('{0}   建议分成{1}个批次，每个批次平均{2}个piece'.format(mat_names, batch_num, batch_size))
        search_batches_GP(orders, batch_num, best_cnt_boards, cut_rim, depart_num, optimization_type, datatime)
        print('----------------------------{0}优化结束---------------------------'.format(mat_names))
    # return batch_size, ratio_max, cnt_boards

calc={
    BoardCategory.orderCabinet:calc_opt_ratio,
    BoardCategory.orderdoor:calc_opt_ratio,
    BoardCategory.waterproofboard:calc_opt_ratio,
}